#-*- coding: utf-8 -*-

from config import db_config

server_type = db_config['server_type']
schema_modulename = 'schema_%s' % server_type
helper_modulename = '%s_helper' % server_type
_schema = __import__(schema_modulename)
_helper = __import__(helper_modulename)


def create_db_connection(server_type=server_type, db_config=db_config):
	if server_type == 'sqlite3':
		return _helper.Connection.create(db_config['dbfile'])
	elif server_type == 'mysql':
		mysql_config = {
			'server': db_config['host'],
			'dbname': db_config['database'],
			'user': db_config['user'],
			'pwd': db_config['pass'],
			'auto_connect': True
		}
		return _helper.Connection.create(**mysql_config)
	else:
		raise Exception('Unsupported database server type.')


def sync_db():
	tables = _schema._tables
	conn = create_db_connection()
	exist_tables = conn.get_tables()
	for t in tables:
		if t[0] not in exist_tables:
			# create
			try:
				conn.execute(t[1])
				yield '%s created.' % t[0]
			except Exception, e:
				print e
				yield '%s skipped!' % t[0]
	conn.close()

